<?php

namespace App\Http\Controllers\Admin;
use App\Model\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    public function login(){
        $userinfo = session()->get('userinfo');
        if($userinfo){
            return redirect('admin/index');
        }
        return view('admin.login');
    }
    public function loginPost(Request $request){

       $request->except('_token');
//       1.数据合法性验证
       $rule = [
           'username' => 'required|max:32',
           'password' => 'required|max:32',
           'code' => 'required|captcha',
       ];
        $messages = [
            'username.required' => '用户名不能为空!',
            'password.required' => '密码不能为空!',
            'code.required' => '验证码不能为空!',
            'code.captcha' => '验证码不正确!',
        ];
        $validator = Validator::make($request->all(),$rule,$messages);
        if($validator->fails()){
            $errors = $validator->errors()->toArray();
            $res = [
                'meta'=>[
                    "msg"=>"获取成功",
                    "status"=>200
                    ],
                'message'=>$errors['code']
            ];
            return json_encode($res);
        }
//        2.账号密码验证
        $input = $request->all();
        $user = User::where('user_name',$input['username'])->first();
        if(!$user){
            $res = [
                'meta'=>[
                    "msg"=>"获取成功",
                    "status"=>200
                ],
                'message'=>['用户不存在！']
            ];
            return json_encode($res);
        }


        if(!Hash::check($input['password'],$user['user_pass'])){

            $res = [
                'meta'=>[
                    "msg"=>"获取成功",
                    "status"=>200
                ],
                'message'=>['用户密码不正确！']
            ];
            return json_encode($res);

        }
        $res = [
            'meta'=>[
                "msg"=>"获取成功",
                "status"=>200
            ],
            'message'=>[]
        ];
        //保存用户信息
        $user_session = ['user_id'=>$user['user_id'],'user_name'=>$user['user_name'],'status'=>$user['status']];
        session()->put('userinfo',$user_session);
        //保存在redis中
        Redis::hmset('user:userinfo:'.$user->user_id,$user->toArray());
        return json_encode($res);


    }
    //用户退出
    public function logout(){
        $userinfo = session()->get('userinfo');
        Redis::del('user:userinfo:'.$userinfo['user_id']);
        session()->flash('userinfo');

        return redirect('/admin/login');
    }
    public function noaccess(){

        return view('errors.error');
    }
}
